package com.demo.apparel.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class COSUploadUtil {

    // 建议改成配置文件读取
    private static final String SECRET_ID = "AKIDyqX5Scu0ufGgvzqUwBD7uXwCvfM3Zu9E";
    private static final String SECRET_KEY = "52ymPsMq9LTWPAmBNM7qQq6CIG0kOr7G";
    private static final String BUCKET_NAME = "apparel-1317894480";
    private static final String REGION = "ap-guangzhou"; // 地域
    public static String upload(MultipartFile file, String folder) throws IOException {
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        ClientConfig clientConfig = new ClientConfig(new Region(REGION));
        COSClient cosClient = new COSClient(cred, clientConfig);

        String fileName = folder + "/" + UUID.randomUUID() + "_" + file.getOriginalFilename();

        InputStream inputStream = file.getInputStream();

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());
        metadata.setHeader("Content-Disposition", "inline");

        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, inputStream, metadata);

        cosClient.putObject(putObjectRequest);

        cosClient.shutdown();

        // 注意 InputStream 由 MultipartFile 管理，不用关闭

        return String.format("https://%s.cos.%s.myqcloud.com/%s", BUCKET_NAME, REGION, fileName);
    }

}
